package com.cloud.admin.controller;

import com.cloud.admin.common.constant.UserConstants;
import com.cloud.admin.common.core.domain.AjaxResult;
import com.cloud.admin.common.core.domain.Ztree;
import com.cloud.admin.common.utils.StringUtils;
import com.cloud.admin.model.entity.SysDept;
import com.cloud.admin.model.entity.SysRole;
import com.cloud.admin.service.SysDeptService;
import com.cloud.admin.shiro.security.ShiroUtils;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;

/**
 * Created on 2019/7/25.
 *
 * @author douhaichao
 */
@RestController
@AllArgsConstructor
@RequestMapping("system/dept")
public class DeptController extends BaseController {

    private final String prefix = "system/dept/";
    private final SysDeptService sysDeptService;

    @RequiresPermissions("system:dept:view")
    @GetMapping()
    public ModelAndView dept() {
        ModelAndView view = super.baseView("dept", prefix + "dept");
        return view;
    }

    @RequiresPermissions("system:dept:list")
    @PostMapping("list")
    public List<SysDept> list(SysDept dept) {
        List<SysDept> deptList = sysDeptService.selectAll(dept);
        return deptList;
    }

    /**
     * 新增部门
     */
    @GetMapping("add/{parentId}")
    public ModelAndView add(@PathVariable("parentId") Long parentId) {
        ModelAndView view = super.baseView("add", prefix + "add");
        view.addObject("dept", sysDeptService.getById(parentId));
        return view;
    }

    /**
     * 新增保存部门
     */
    @RequiresPermissions("system:dept:add")
    @PostMapping("add")
    public AjaxResult addSave(@Validated SysDept dept) {
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(sysDeptService.checkDeptNameUnique(dept))) {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(ShiroUtils.getLoginName());
        dept.setCreateTime(new Date());
        return toAjax(sysDeptService.insertDept(dept));
    }

    /**
     * 修改
     */
    @GetMapping("edit/{deptId}")
    public ModelAndView edit(@PathVariable("deptId") Integer deptId) {
        ModelAndView view = super.baseView("edit", prefix + "edit");
        SysDept dept = sysDeptService.getDeptInfo(deptId);
        if (StringUtils.isNotNull(dept) && 100 == deptId) {
            dept.setParentName("无");
        }
        view.addObject("dept", dept);
        return view;
    }

    /**
     * 保存
     */
    @RequiresPermissions("system:dept:edit")
    @PostMapping("edit")
    public AjaxResult editSave(@Validated SysDept dept) {
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(sysDeptService.checkDeptNameUnique(dept))) {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }

        dept.setUpdateBy(ShiroUtils.getLoginName());
        dept.setUpdateTime(new Date());
        return toAjax(sysDeptService.updateDept(dept));
    }

    /**
     * 删除
     */
    @RequiresPermissions("system:dept:remove")
    @GetMapping("remove/{deptId}")
    public AjaxResult remove(@PathVariable("deptId") Integer deptId) {
        if (sysDeptService.count(new SysDept().setParentId(deptId)) > 0) {
            return AjaxResult.warn("存在下级部门,不允许删除");
        }
        if (sysDeptService.checkDeptExistUser(deptId)) {
            return AjaxResult.warn("部门存在用户,不允许删除");
        }
        return toAjax(sysDeptService.removeById(deptId));
    }

    /**
     * 校验部门名称
     */
    @PostMapping("checkDeptNameUnique")
    public String checkDeptNameUnique(SysDept dept) {
        return sysDeptService.checkDeptNameUnique(dept);
    }

    /**
     * 选择部门树
     */
    @GetMapping("selectDeptTree/{deptId}")
    public ModelAndView selectDeptTree(@PathVariable("deptId") Long deptId) {
        ModelAndView view = super.baseView("tree", prefix + "tree");
        view.addObject("dept", sysDeptService.getById(deptId));
        return view;
    }

    /**
     * 加载部门列表树
     */
    @GetMapping("treeData")
    public List<Ztree> treeData() {
        List<Ztree> ztrees = sysDeptService.selectDeptTree(new SysDept());
        return ztrees;
    }

    /**
     * 加载角色部门（数据权限）列表树
     */
    @GetMapping("roleDeptTreeData")
    public List<Ztree> deptTreeData(SysRole role) {
        List<Ztree> ztrees = sysDeptService.roleDeptTreeData(role);
        return ztrees;
    }
}
